package com.szh.mysobproject.viewmodel.discover

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.szh.mysobproject.http.ServiceCreator
import com.szh.mysobproject.http.request.api.PhotoApi
import com.szh.mysobproject.http.response.model.WallpaperBannerBean
import com.szh.mysobproject.http.response.model.WallpaperBean
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber

/**
 * @author : create by  szh
 * @date : 2022/7/14 14:53
 * @desc :发现页的viewModel
 */

class DiscoverViewModel : ViewModel() {

    private val mPhotoApi by lazy { ServiceCreator.create<PhotoApi>() }

    //当前请求的图片页码
    private val _currentPhotoPage = MutableLiveData<Int>()

    //轮播图集合
    private val _bannerList = MutableLiveData<List<WallpaperBannerBean.Data>>()
    val wallpaperBannerList: LiveData<List<WallpaperBannerBean.Data>> get() = _bannerList

    // 缓存的所有图片集合
    private val _cacheVerticalPhotoList = MutableLiveData<List<WallpaperBean.Res.Vertical>>()
    val cacheVerticalPhotoList: LiveData<List<WallpaperBean.Res.Vertical>> get() = _cacheVerticalPhotoList

    // 当前加载更多的集合
    private val _verticalPhotoList = MutableLiveData<List<WallpaperBean.Res.Vertical>>()
    val verticalPhotoList: LiveData<List<WallpaperBean.Res.Vertical>> get() = _verticalPhotoList

    fun loadMorePhotoList(limit: Int = 10) {
        viewModelScope.launch {
            //当前默认第0页
            val currentPage = _currentPhotoPage.value ?: 0
            //设置本次请求需要跳过几张照片
            val skip = currentPage * 10
            Timber.d("currentPage：$currentPage skip：$skip")
            runCatching {
                //查询多少条数据，跳过多少条数据
                withContext(Dispatchers.IO) {
                    mPhotoApi.loadWallpaperList(limit, skip)
                }
            }.onSuccess { response ->
                val responseData = response.res.vertical
                if (0 == response.code) {
                    val cachePhotoList = (_cacheVerticalPhotoList.value ?: listOf()).toMutableList()
                    cachePhotoList.addAll(responseData)
                    // 设置缓存的全部图片集合
                    _cacheVerticalPhotoList.value = cachePhotoList
                    // 本次加载更多的图片集合
                    _verticalPhotoList.value = responseData
                    // 本次查询成功，当前页码 +1
                    _currentPhotoPage.value = currentPage + 1
                }
            }.onFailure {
                it.printStackTrace()
            }
        }
    }
}